package com.example.chamberlainserver.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import lombok.Data;

/**
 * JWT工具类，用于生成和验证JWT令牌
 */
@Component
public class JwtTokenUtil {

    // Token有效期为24小时
    public static final long JWT_TOKEN_VALIDITY = 24 * 60 * 60 * 1000;

    @Value("${jwt.secret:chamberlain_secret_key}")
    private String secret;

    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 从token中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从token中获取指定的claim
     */
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 解析token获取所有的claims
     */
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 检查token是否过期
     */
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 为用户生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }
    
    /**
     * 为用户生成token，包含用户ID和角色信息
     */
    public String generateToken(UserDetails userDetails, int userId, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("role", role);
        return doGenerateToken(claims, userDetails.getUsername());
    }

    /**
     * 生成token的过程
     * 1. 定义token的声明，如发行人、过期时间、主题和ID
     * 2. 使用HS512算法和密钥对JWT进行签名
     * 3. 根据JWS紧凑序列化将JWT转换为字符串
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取用户ID
     */
    public Integer getUserIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("userId", Integer.class));
    }

    /**
     * 验证token
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
    
    /**
     * 从token中获取用户角色
     */
    public String getRoleFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("role", String.class));
    }
    
    /**
     * 从token中获取完整的用户信息
     */
    public UserInfo getUserInfoFromToken(String token) {
        Claims claims = getAllClaimsFromToken(token);
        String username = claims.getSubject();
        Integer userId = claims.get("userId", Integer.class);
        String role = claims.get("role", String.class);
        
        return new UserInfo(userId, username, role);
    }
    
    /**
     * 用户信息数据类
     */
    @Data
    public static class UserInfo {
        private final Integer userId;
        private final String username;
        private final String role;
        
        public UserInfo(Integer userId, String username, String role) {
            this.userId = userId;
            this.username = username;
            this.role = role;
        }
    }
}